import React from "react";
import {Icon, Popover, Select, Popconfirm} from 'antd';
import {connect} from 'react-redux';
import ReportDistributionService from "containers/data-center/report-distribution/report-distribution.service";
import {messages} from "share/common";
import menuRoute from "routes/menuRoute";
import BasicInfo from 'components/basic-info';
import SelectByBtn from "components/template/select-by-btn";
import 'styles/data-center/report-distribution/permission-detail/report-distribution-permission-details.scss';
import ResizeTable from 'components/resize-table';
import DataPermissionViewer from 'containers/data-center/report-distribution/permission-detail/data-permission-viewer';
const Option = Select.Option;

class ReportDistributionPermissionDetails extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      data: [],
      pagination: {
        total: 0,
        current: 1,
        page: 0,
        pageSize: 10,
      },
      //基本信息中有扩展字段，这个扩展字段是动态的，需要请求详情完毕之后，才能确认，
      //这里先确定固定的字段
      infoList: [
        {
          type: 'input',
          label: messages('data-center.key33')/*报表名称*/,
          id: 'reportName',
          disabled: true
        },
        {
          type: 'input',
          label: messages('common.remark')/*备注*/,
          id: 'remark',
          disabled: true
        },
        {
          type: 'input',
          label: messages('data-center.key123')/*适用人员*/,
          id: '_grantName',
          disabled: true
        },
        {
          type: 'input',
          label: messages('data-center.key35')/*权限范围*/,
          id: '_permissionName',
          disabled: true
        },
        {
          type: 'switch',
          label: messages('setting.key326'/*状态*/),
          id: 'enable'
        },

      ],
      reportDetail: {},
      //如果是自定义人员组
      columnsUserGroup: [
        {
          title: messages('data-center.key109')/*人员组编码*/,
          dataIndex: "code",
          render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }
        },
        {
          title: messages('data-center.key110')/*人员组名称*/,
          dataIndex: "name",
          render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }
        },
        {
          title: messages('data-center.key111')/*人员组描述*/,
          dataIndex: "comment",
          render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }
        },
        {
          title: messages('common.operation'),
          dataIndex: 'id',
          width: '10%',
          render: (value, record) => {
            return (
              <Popconfirm onConfirm={() => this.handleDelete(value, record)}
                          title={messages('common.confirm.delete')}>
                <a onClick={e => {
                  e.preventDefault();
                  e.stopPropagation()
                }}>
                  {messages('common.delete')}
                </a>
              </Popconfirm>
            )
          }
        }
      ],
      columns: [
        {
          title: messages('report-distribution.key14'/*工号*/),
          dataIndex: "employeeId",
          render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }
        },
        {
          title: messages('report-distribution.key15'/*姓名*/),
          dataIndex: "fullName",
          render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }
        },
        {
          title: messages('report-distribution.key16'/*公司名称*/),
          dataIndex: "companyName",
          render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }
        },
        {
          title: messages('report-distribution.key17'/*部门*/),
          dataIndex: "departmentName",
          render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }
        },
        {
          title: messages('common.operation'),
          dataIndex: 'userOID',
          width: '10%',
          render: (value, record) => {
            return (
              <Popconfirm onConfirm={() => this.handleDelete(value, record)}
                          title={messages('common.confirm.delete')}>
                <a onClick={e => {
                  e.preventDefault();
                  e.stopPropagation()
                }}>
                  {messages('common.delete')}
                </a>
              </Popconfirm>
            )
          }
        }
      ],
      grant: undefined,
      ReportDistribution: menuRoute.getRouteItem('data-report-distribution', 'key'),
    }
  }

  componentDidMount() {
    this.getReportPermissionDetail(this.props.params.permission_id);
  }

  //获取权限详情
  getReportPermissionDetail = (id) => {
    let obj = {
      id,
    }
    if (this.props.params.permission_user === "user") {
      obj.grantCode = "user";
    }
    if (this.props.params.permission_user === "userGroup") {
      obj.grantCode = "userGroup";
    }
    ReportDistributionService.getPermissionList()
      .then((data) => {
        ReportDistributionService.getReportPermissionDetail(obj)
          .then(res => {
            this.setState({
              grant: this.props.params.permission_user,
              reportDetail: res.data
            });
            this.getPersonList();
          })
      });
  }


  //翻页查询人
  //翻页查询人员组
  getPersonList = () => {
    let {pagination} = this.state;
    let obj = {
      id: this.props.params.permission_id,
      page: pagination.page,
      size: pagination.pageSize,
    }
    let type = this.props.params.permission_user;
    ReportDistributionService.getReportPermissionUser(obj,type)
      .then((response) => {
        let data = response.data;
        pagination.total = Number(response.headers['x-total-count']);
        this.setState({
          pagination,
          data: type === "user" ? data.users : data.userGroups
        })
      })
  }

  //授权范围
  renderDataGrant = (grant) => {
    switch (grant) {
      case "user": {
        //只有当时用户的时候，才显示选择人员
        return this.renderNonFullVisible();
      }
      case "userGroup": {
        return this.renderUserGroup();
      }
      default: {
        return this.renderFullVisible();
      }
    }
  }

  //全员可见渲染
  renderFullVisible = () => {
    return (
      <div className="img-center"/>
    )
  };

  //渲染人员组
  renderUserGroup = () => {
    const {data, pagination, columnsUserGroup, loading} = this.state;

    return (
      <div>
        <div className="table-header">
          <div className="table-header-title">
            {messages("common.total", {total: pagination.total ? pagination.total : '0'})}
          </div>
          {/* 共搜索到total条数据 */}
          <div className="table-header-buttons">
            <div>
              <span className="pull-left">
                <SelectByBtn
                  type={'user_group'}
                  title={messages('data-center.key112')/*添加人员组*/}
                  labelKey={'name'}
                  buttonType={"primary"}
                  valueKey={'id'}
                  onConfirm={this.addPersonGroupByCon}/>
              </span>
            </div>
          </div>
        </div>
        <ResizeTable
          columns={columnsUserGroup}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          bordered
          onChange={this.onChangePager}
          className="clear"
        />
      </div>
    )
  }
  //添加人员组
  addPersonGroupByCon = (result) => {
    let userGroups = [];
    result.map(item => {
      userGroups.push(item.value)
    });
    this.addDeleteUser(this.props.params.id, this.props.params.permission_id, userGroups, false)
  };

  //不是全员可见
  renderNonFullVisible = () => {
    const {data, pagination, columns, loading} = this.state;
    return (
      <div>
        <div className="table-header">
          <div className="field-title">
            {messages('data-center.key123')/*适用人员*/}
          </div>
          <div className="table-header-title">
            {messages("common.total", {total: pagination.total ? pagination.total : '0'})}
          </div>
          {/* 共搜索到total条数据 */}
          <div className="table-header-buttons">
            <div>
              <span className="pull-left">
                <SelectByBtn
                  type={'add_employee'}
                  title={messages('report-distribution.key23'/*按条件添加员工*/)}
                  labelKey={'fullName'}
                  buttonType={"primary"}
                  valueKey={'userOID'}
                  onConfirm={this.addStaffsByCon}/>
              </span>
            </div>
          </div>
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          bordered
          onChange={this.onChangePager}
          className="clear"
        />
      </div>
    )
  }

  //过滤重复数据后添加员工
  addStaffsByCon = (result) => {
    let users = result.map(item => item.value);
    this.addDeleteUser(this.props.params.id, this.props.params.permission_id, users, false)
  };

  //添加或者删除用户,添加或者删除人员组
  addDeleteUser = (reportId, permissionId, users, isDelete) => {
    let that = this;
    let obj = _getOperationUsers(reportId, permissionId, users, isDelete);
    ReportDistributionService.updateReportPermissionUser(obj)
      .then((data) => {
        this.getReportPermissionDetail(this.props.params.permission_id);
      });
    /*
    * 处理成后端接口请求需要的格式
    * */
    function _getOperationUsers(sourceReportId, permissionId, users, isDelete) {
      let obj = {};
      obj.sourceReportId = sourceReportId;
      obj.id = permissionId;
      obj.permission = [];
      let grant = [];
      if (that.props.params.permission_user === "user") {
        users.map(item => {
          let u = {};
          u.grantProp = 'user';
          u.grantValue = item.userOID;
          isDelete ? u.id = item._origin.id : "";
          grant.push(u)
        });
      }
      if (that.props.params.permission_user === "userGroup") {
        users.map(item => {
          let u = {};
          u.grantProp = 'userGroup';
          u.grantValue = item.id;
          //每一个关联的用户的id,代表删除
          isDelete ? u.id = item._origin.id : "";
          grant.push(u)
        });
      }
      obj.grant = grant;
      return obj;
    }
  }
  //分页点击
  onChangePager = (pagina, filters, sorter) => {
    let {pagination} = this.state;
    pagination.current = pagina.current;
    pagination.page = pagina.current - 1;
    pagination.pageSize = pagina.pageSize;
    this.setState({
      pagination
    }, () => {
      this.getPersonList();
    })
  };

  //删除员工列表,暂存删除操作及数据
  handleDelete = (OID, record) => {
    this.addDeleteUser(this.props.params.id, this.props.params.permission_id, [record], true)
  };
  back = () => {
    let route = menuRoute.getRouteItem('data-report-distribution-permission', 'key');
    let path = route.url.replace(':id', this.props.params.id);
    path = path.replace(':name', this.state.reportDetail.reportName);
    this.context.router.push(path);
  }
  render() {
    const {infoList, reportDetail} = this.state;
    return (
      <div className="report-distribution-details-permission-wrap">
        <BasicInfo infoList={infoList}
                   infoData={reportDetail}
                   isHideEditBtn={true}
        />
        <DataPermissionViewer permissionData={reportDetail.permission}/>
        {this.renderDataGrant(this.state.grant)}
        <div style={{fontSize: 14, margin: '20px 0',}}>
          <a onClick={this.back}>
            <Icon type="rollback"/>{messages("common.back")/*返回*/}
          </a>
        </div>
      </div>
    );
  }
}


ReportDistributionPermissionDetails.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
  }
}

export default connect(mapStateToProps)(ReportDistributionPermissionDetails);

